<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".__("Member Commission");
$page_title=__("Member Commission");

if(!$pv["task"]["Member Commission"]){
 $errmsg=format_err(__("You do not have the privilege to access member commission."));
            
 print format_admin_page($errmsg, $this_title);
 exit();
}

$item_per_page=$vars["admin_item_per_page"];
$td_width=180;

$r_status=array("confirmed","cancelled");
$r_status_d=array("confirmed"=>__("Confirmed"),"cancelled"=>__("Cancelled"));
$r_type=array('all','r','p','m','1','2','3','u','t','cf');
$r_type_d=array('all'=>__("All"),'r'=>__("Sponsor Commission"),'p'=>__("Pairing"),'m'=>__("Matching"),'1'=>__("Pool 1"),'2'=>__("Pool 2"),'3'=>__("Pool 3"),'u'=>__("Unilevel"),'t'=>__("Stockist Commission"),'cf'=>__("Carry Forward"));
$r_month=array('1','2','3','4','5','6','7','8','9','10','11','12');
$r_month_d=array('1'=>__("1"),'2'=>__("2"),'3'=>__("3"),'4'=>__("4"),'5'=>__("5"),'6'=>__("6"),'7'=>__("7"),'8'=>__("8"),'9'=>__("9"),'10'=>__("10"),'11'=>__("11"),'12'=>__("12"));
for($i=2009,$j=0,$t=ndate("Y");$i<=$t;$i++){
 $r_year[$j++]=$i;
 $r_year_d[$i]=$i;
}

//#####COMMISSION GET#####
if($_GET["__req"]){
 //ERROR CHECK
 if(!in_array($get_s["type"], $r_type)){
  $errmsg.=__("Please select a commission first.")."<br />\n";
 }
 if(($get_s["monthf"] + $get_s["yearf"] * 12) > ($get_s["montht"] + $get_s["yeart"] * 12)){
  $errmsg.=__("The selected Date From is greater than the Date To.")."<br />\n";
 }
 if($get_s['type']=='cf' && !strlen($get_s['uid'])){
	$errmsg.=__("Please provide a member ID.")."<br />";
 }

 if(!$errmsg){
  $comm_query = true;

  //format search string
  if($get_s['uid']){
   $uid_q=format_search_field("uid", $get_d['uid']);
  }else{
   $uid_q="1=1";
  }
  //status query
  foreach($r_status as $status){
   if($get_s["_status_$status"]){
    $status_q.=($status_q? "," : "")."'$status'";
   }
  }
  $status_q=$status_q? "status in ($status_q)" : "1=1";
  //date range
  $monthyear_from=$get_s["monthf"] + $get_s["yearf"] * 12;
  $monthyear_to=$get_s["montht"] + $get_s["yeart"] * 12;
  //type
  $type_q=$get_s["type"]!='all'? "type='$get_d[type]'" : "1=1";

  if($get_s['type'] == 'cf'){
	//get the downlines for this user
	$t=@mysql_num_rows($r=mysql_query("select id from $db->users where matrix_upline='$get_d[uid]' and status!='terminated'"));
	$downline_id='';
	for($i=0;$i<$t;$i++){
		$down = mysql_fetch_assoc($r);
		$downline_id.=($downline_id? "," : "").$down['id'];
	}
	$from_time = mktime(0,0,0,$get_s['monthf'],1,$get_s['yearf']);
	$to_time = mktime(0,0,0,$get_s['montht']+1,0,$get_s['yeart']);
	$from_date = date('Y-m-d', $from_time);
	$to_date = date('Y-m-d', $to_time);
	$count_sql="select count(*) from $db->member_cf where uid in ($downline_id) and cdate>='$from_date' and cdate<='$to_date'";
	$sum_sql="select sum(amount) from $db->member_cf where uid in ($downline_id) and cdate>='$from_date' and cdate<='$to_date'";
	$record_sql="select * from $db->member_cf where uid in ($downline_id) and cdate>='$from_date' and cdate<='$to_date' order by cdate desc limit <%limit_start%>, <%limit%>";
  }else{
	  $count_sql="select count(*) from $db->member_comm where $uid_q and $type_q and $status_q and month + year * 12>=$monthyear_from and month + year * 12<=$monthyear_to";
	  $sum_sql="select sum(amount) from $db->member_comm where $uid_q and $type_q and $status_q and month + year * 12>=$monthyear_from and month + year * 12<=$monthyear_to";
	  $record_sql="select * from $db->member_comm where $uid_q and $type_q and $status_q and month + year * 12>=$monthyear_from and month + year * 12<=$monthyear_to order by year, month limit <%limit_start%>, <%limit%>";
  }
 }

 $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}
//#####END COMMISSION GET#####

$form_fields=array("uid"=>"","type"=>"a","monthf"=>"3","yearf"=>"2009","montht"=>ndate("n"),"yeart"=>ndate("Y"));
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=(!$get_s["__req"]? $default : $get_h[$field]);
}
$type_select=build_select($r_type, $r_type_d, $dis["type"], "type", $inputbox_style);
$monthf_select=build_select($r_month, $r_month_d, $dis["monthf"], "monthf");
$yearf_select=build_select($r_year, $r_year_d, $dis["yearf"], "yearf");
$montht_select=build_select($r_month, $r_month_d, $dis["montht"], "montht");
$yeart_select=build_select($r_year, $r_year_d, $dis["yeart"], "yeart");

$comm_ui=($errmsg || $msg? $errmsg.$msg : "").
"<form name='comm_form' method='get' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='nav' value=\"$get_h[nav]\" />
<table class='pbt_table'>
 <tr>
  <td width='$td_width'>".__("Member ID").__(":")."</td>
  <td><input type='text' name='uid' value=\"$dis[uid]\" $inputbox_style /></td>
 </tr>
 <tr>
  <td width='$td_width'>".__("Commission Type").__(":")." ".__("*")."</td>
  <td>$type_select</td>
 </tr>
 <tr>
  <td width='$td_width'>".__("Commission Status").__(":")." ".__("*")."</td>
  <td><input type='checkbox' name='_status_confirmed' ".(!$get_s['__req'] || $get_s['_status_confirmed']? "checked='checked'" : '')." id='st_confirmed' /> <label for='st_confirmed'>".$r_status_d['confirmed']."</label><br />\n
      <input type='checkbox' name='_status_cancelled' ".($get_s['_status_cancelled']? "checked='checked'" : '')." id='st_cancelled' /> <label for='st_cancelled'>".$r_status_d['cancelled']."</label></td>
 </tr>
 <tr>
  <td width='$td_width'>".__("Date Range").__(":")." ".__("*")."</td>
  <td>".__("From").__(":")." ".__("Month").__(":")." $monthf_select ".__("Year").__(":")." $yearf_select<br />\n
      ".__("To").__(":")." ".__("Month").__(":")." $montht_select ".__("Year").__(":")." $yeart_select</td>
 </tr>
 <tr>
  <td colspan='2' style='padding:20px 0;' class='center'><input type='submit' value=\"".__("Generate")."\" /></td>
 </tr>
 <tr>
  <td colspan='2' style='font-style:italic; font-size:12px;'>".__("Note:")." ".__("Sponsor bonus is calculated immediately, Pairing and Matching are calculated everyday, while Pool, Unilevel, and Stockist Commission are calculated at month end.")."</td>
 </tr>
</table>";

if($comm_query){
 $cur_page=$_GET["nav"];
 $total_record=@mysql_result(mysql_query($count_sql), 0);
 $total_page=ceil($total_record/$item_per_page);
 $page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
 $limit_start=($page-1)*$item_per_page;
 $nav_link=format_page_admin($page, $total_page, $this_file);
 $this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
 $grand_total = @mysql_result(mysql_query($sum_sql), 0) or 0;
 $k=0;
 for($i=0;$i<$this_page_total;$i++){
  $comm=mysql_fetch_assoc($r);
  $this_no = ($page - 1) * $item_per_page + $i + 1;
  if($get_s['type']=='cf'){
	if($comm['uid'] && !isset($users[$comm['uid']])){
		$users[$comm['uid']] = get_user_detail_by_id($comm['uid']);
	}
   $comm_row.="
	  <tr class='row$k'>
	   <td>".$this_no."</td>
	   <td>$comm[uid], {$users[$comm['uid']]['name']}</td>
	   <td class='number'>".number_format($comm["amount"], 2)."</td>
	   <td>".date($vars['date_format_short'], strtotime($comm['cdate']))."</td>
	  </tr>";
  }else{
	  if(!$users[$comm['uid']]){
	   $users[$comm['uid']] = get_user_detail_by_id($comm['uid']);
	  }
	  if($get_s["type"]!="all"){
	   $comm_row.="
	  <tr class='row$k'>
	   <td>".$comm["id"]."</td>
	   <td>".$comm["uid"]." (".$users[$comm['uid']]['name'].")</td>
	   <td>".$r_type_d[$comm["type"]]."</td>".(in_array($comm["type"], array('r','u','t'))? "
	   <td>".$comm["cid"]."</td>" : "")."".(in_array($comm["type"], array('m'))? "
	   <td>".$comm["pid"]."</td>" : "").(in_array($comm["type"], array('r','m','u','t'))? "
	   <td>".$comm["from_uid"]."</td>" : "").(in_array($comm["type"], array('p'))? "
	   <td class='number'>".$comm['leg1']."(ID:{$comm['leg1_id']} BV:{$comm['leg1_amount']}) + {$comm['leg2']}(ID:{$comm['leg2_id']} BV:{$comm['leg2_amount']})</td>
	   <td class='number'>".number_format($comm['paired_unit'])." (Pairing ".number_format($comm['volume_type'])."BV)</td>" : "")."
	   <td class='number'>".number_format($comm["amount"], 2)."</td>".(in_array($comm["type"], array('r','m','u','t'))? "
	   <td>".$comm["level"]."</td>" : "").(in_array($comm['type'], array('r','m','1','2','3','u','t'))? "
	   <td class='number'>".$comm["percent"]."</td>" : "")."
	   <td>".$r_status_d[$comm['status']]."</td>
	   <td>".(in_array($comm["type"], array('1','2','3','u'))? date('M-Y', mktime(0,0,0,$comm['month'],1,$comm['year'])) : date($vars['date_format_short'], mktime(0, 0, 0, $comm["month"], $comm["day"], $comm["year"])))."</td>
	  </tr>";
	  }else{
	   $comm_row.="
	  <tr class='row$k'>
	   <td>".$comm["id"]."</td>
	   <td>".$comm["uid"]." (".$users[$comm['uid']]['name'].")</td>
	   <td>".$r_type_d[$comm["type"]]."</td>
	   <td>".$comm["cid"]."</td>
	   <td>".$comm["pid"]."</td>
	   <td>".$comm["from_uid"]."</td>
	   <td class='number'>".($comm['type']=='p'? $comm['leg1']."(ID:{$comm['leg1_id']} BV:{$comm['leg1_amount']}) + {$comm['leg2']}(ID:{$comm['leg2_id']} BV:{$comm['leg2_amount']})" : "")."</td>
	   <td class='number'>".($comm['type']=='p'? number_format($comm['paired_unit'])." (Pairing ".number_format($comm['volume_type'])."BV)" : "")."</td>
	   <td class='number'>".number_format($comm["amount"], 2)."</td>
	   <td>".$comm["level"]."</td>
	   <td class='number'>".$comm["percent"]."</td>
	   <td>".$r_status_d[$comm['status']]."</td>
	   <td>".(in_array($comm["type"], array('1','2','3','u'))? date('M-Y', mktime(0,0,0,$comm['month'],1,$comm['year'])) : date($vars['date_format_short'], mktime(0, 0, 0, $comm["month"], $comm["day"], $comm["year"])))."</td>
	  </tr>";
	  }
  }
  $k=1-$k;
 }

 //listing text
 $listing_text=replace_tag(__("Listing <%x%> <%comm%>."), array("<%x%>"=>strval($total_record), "<%comm%>"=>$total_record>1? __("commissions") : __("commission")));

 //listing
 $comm_list=
 "<h3>".replace_tag(__("<%title%> Total: <%x%>"), array("<%title%>"=>$r_type_d[$get_s["type"]], "<%x%>"=>number_format($grand_total, 2)))."</h3>
 $listing_text $nav_link
 <table class='aml_table' style='width:800px;'>
  <tr class='aml_header'>".($get_s['type'] == 'cf'? "
   <td>".__("No.")."</td>
   <td>".__("Downline")."</td>
   <td>".__("Amount")."</td>
   <td>".__("Carry Forward Date")."</td>" 
   
   :
   
   ($get_s["type"]!="all"? "
   <td>".__("ID")."</td>
   <td>".__("UID")."</td>
   <td>".__("Type")."</td>".(in_array($comm["type"], array('r','u','t'))? "
   <td>".__("Sale ID")."</td>" : "")."".(in_array($comm["type"], array('m'))? "
   <td>".__("Comm ID")."</td>" : "").(in_array($comm["type"], array('r','m','u','t'))? "
   <td>".__("From UID")."</td>" : "").(in_array($comm["type"], array('p'))? "
   <td>".__("Leg")."</td>
   <td>".__("Paired Unit")."</td>" : "")."
   <td>".__("Amount")."</td>".(in_array($comm["type"], array('r','m','u','t'))? "
   <td>".__("Level")."</td>" : "").(in_array($comm['type'], array('r','m','1','2','3','u','t'))? "
   <td>".__("Percent")."</td>" : "")."
   <td>".__("Status")."</td>
   <td>".__("Date")."</td>
  </tr>"

  :
  "
   <td>".__("ID")."</td>
   <td>".__("UID")."</td>
   <td>".__("Type")."</td>
   <td>".__("Sale ID")."</td>
   <td>".__("Comm ID")."</td>
   <td>".__("From UID")."</td>
   <td>".__("Leg")."</td>
   <td>".__("Paired Unit")."</td>
   <td>".__("Amount")."</td>
   <td>".__("Level")."</td>
   <td>".__("Percent")."</td>
   <td>".__("Status")."</td>
   <td>".__("Date")."</td>
  </tr>"))."
  $comm_row
 </table>";
}

$content="
<h2>$page_title</h2>
$comm_ui
$comm_list";
           
print format_admin_page($content, $this_title);
?>